<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { GetConfigurationList, GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/messageGroup'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm: any = ref({
  groupName: '',
  type: undefined,
  relateConfigArray: [],
})
const rules = reactive({
  groupName: [
    { required: true, message: '请输入组名', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'blur' },
  ],
})

const typeArr = [
  {
    value: 1,
    label: '企微欢迎语',
  },
  {
    value: 2,
    label: '快捷消息',
  },
  {
    value: 3,
    label: '灵活欢迎语',
  },
]

interface ConfigurationType {
  id: number
  title: string
}
const ConfigurationList = ref<ConfigurationType[]>([])

const id = route.query.id as string

function SortList(way: string, index: number) {
  if (way === 'up') {
    if (index === 0) {
      return
    }
    const temp = ConfigurationList.value[index - 1]
    ConfigurationList.value[index - 1] = ConfigurationList.value[index]
    ConfigurationList.value[index] = temp
  }
  else {
    if (index === ConfigurationList.value.length - 1) {
      return
    }
    const temp = ConfigurationList.value[index + 1]
    ConfigurationList.value[index + 1] = ConfigurationList.value[index]
    ConfigurationList.value[index] = temp
  }
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const idToIndexMap = new Map()
      ConfigurationList.value.forEach((item, index) => {
        idToIndexMap.set(item.id, index)
      })
      ruleForm.value.relateConfigArray = ruleForm.value.relateConfigArray
        .map((id: any) => ({ id, index: idToIndexMap.get(id) })) // 将ID与其索引关联
        .filter((item: any) => item.index !== undefined) // 过滤掉不在ConfigurationList中的ID
        .sort((a: any, b: any) => a.index - b.index) // 根据索引排序
        .map((item: any) => item.id) // 提取排序后的ID
      // console.log(ConfigurationList.value)
      // console.log(ruleForm.value.relateConfigArray)
      if (id) {
        // 编辑
        ruleForm.value.id = id
        PutModifyData(ruleForm.value).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'messageGroup' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`编辑失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`编辑失败。${errorStr}`)
            }
          }
        })
      }
      else {
        // 添加
        PostCreateData(ruleForm.value).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.EmptyMessage()
            router.push({ name: 'messageGroup' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`添加失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`添加失败。${errorStr}`)
            }
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

watch(ruleForm, (newValue) => {
  detailData.RememberMessage(newValue)
}, { deep: true })

onMounted(async () => {
  await GetConfigurationList().then((res: any) => {
    if (res.statusCode === 200) {
      ConfigurationList.value = res.data
      ConfigurationList.value.forEach((item) => {
        // eslint-disable-next-line ts/ban-ts-comment
        // @ts-expect-error
        item.id = item.id.toString()
      })
    }
  })
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        // ConfigurationList.value =
      }
    })
  }
  else {
    ruleForm.value = detailData.GetMessageData()
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="10">
            <ElFormItem label="组名" prop="groupName">
              <el-input v-model="ruleForm.groupName" style="width: 300px;" placeholder="请输入组名" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="14">
            <ElFormItem label="类型" prop="type">
              <el-select v-model="ruleForm.type" placeholder="请选择" style="width: 300px;">
                <el-option v-for="item in typeArr" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="关联配置" prop="relateConfigArray">
              <el-checkbox-group v-model="ruleForm.relateConfigArray">
                <div v-for="(item, index) in ConfigurationList" :key="item.id" class="check-option">
                  <el-checkbox :label="`${item.id} - ${item.title}`" :value="item.id" style="width: 260px;" />
                  <el-button-group class="ml-4">
                    <el-button :icon="ArrowUp" @click="SortList('up', index)" />
                    <el-button :icon="ArrowDown" @click="SortList('down', index)" />
                  </el-button-group>
                </div>
              </el-checkbox-group>
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

  <style lang="scss" scoped>
  :deep(.el-date-editor) {
    width: 100%;
  }

  .tag {
    max-width: 300px;
    color: red;
  }

  .check-option {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  </style>
